package com.alibam.core.wechat.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

public class PayUtils {

	/**
	 * 按对象字幕顺序创建签名
	 * 
	 * @param objKVMap
	 * @param characterEncoding
	 * @param apiKey
	 * @return
	 */
	public static String createSign(Map<String, String> objKVMap, String characterEncoding,
			String apiKey) {
		StringBuffer sb = new StringBuffer();
		Set<Entry<String, String>> es = objKVMap.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			String k = (String) entry.getKey();
			String v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + apiKey);
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding)
				.toUpperCase();
		
		System.out.println("createSign: " + sb.toString());
		return sign;
	}

	/**
	 * 获取对象属性及属性值的Map。
	 * 
	 * @param o
	 * @return
	 */
	public static TreeMap<String, String> generateObjKVMap(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		TreeMap<String, String> infoMap = new TreeMap<String, String>();
		for (int i = 0; i < fields.length; i++) {
			String temp = (String) getFieldValueByName(fields[i].getName(), o);
			if (null != temp) {
				infoMap.put(fields[i].getName(), temp);
			}
		}
		return infoMap;
	}

	/**
	 * 提取对象属性值
	 * 
	 * @param fieldName
	 * @param o
	 * @return
	 */
	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 创建随机字串
	 * 
	 * @param length
	 * @return
	 */
	public static String createNoncestr(int length) {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < length; i++) {
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}

	/**
	 * 创建随机字串，固定长度。
	 * 
	 * @return
	 */
	public static String createNoncestr() {
		return createNoncestr(16);
	}

	public static void main(String[] args) {
		System.out.println(createNoncestr());
	}
}
